package xframe.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.*;

import xframe.util.db.Row;
import xframe.util.db.Transaction;

public class SystemLogger {
	private String cookie_id;
	private String session_id;
	private int visit_cnt ;
	private int pg_cnt;
	private String parameter;
	private String contents_url ;
	private String referer ;
	private String ip;
	private String browser;
	private String before_log_time;
	private String before_url;
	private Date log_time;
	private long	startTime;
	private long	endTime;
	private long	before_staying_time = 0;
	private long	loading_time = 0;
	String com = "akami.pe.kr";
	HashMap	req	;
	
	public SystemLogger(HttpServletResponse response, HttpServletRequest request){
		HttpSession session = request.getSession();
		
		session_id 		= 	session.getId();
		parameter 		= 	request.getQueryString();
		if(parameter !=	null){
			contents_url 	= 	request.getRequestURL().toString()+"/"+parameter;
		}else{
			contents_url 	= 	request.getRequestURL().toString();
		}
		ip 				= 	request.getRemoteAddr();
		referer 		= 	request.getHeader("referer"); 
		startTime		=	System.nanoTime();
		browser		= 	request.getHeader("user-agent"); 
		
		req			=	getRequestInfo(request);
		
		req.put("session_id",session_id);
		req.put("parameter",parameter);
		req.put("contents_url",contents_url);
		req.put("referer",referer);
		req.put("ip",ip);
		req.put("browser",browser);
		req.put("pgname",request.getAttribute("pgname"));
		//WhoIS whois =new WhoIS();
		//try {
			//System.out.println("***************************whois : "+whois.whois(ip));
			//req.put("whois",whois.whois2(ip));
		//} catch (Exception e1) {
			// TODO Auto-generated catch block
		//	e1.printStackTrace();
		//}
		
		
		try {
			cookie_id = CookieUtil.getCookie(request,com+"-"+"id");
			
			String todayUniqeCookie = CookieUtil.getCookie(request,com+"-"+"today");
			//## 무조건  오늘 발급한 쿠키가 아니면 디비에 접속카운트를 증가시킨다.
			setTodayUniqeCookie(response, request);

			//1.사이트에 처음 온 단말기라면 쿠키를 만들어서 준다.
			if(cookie_id == null){
				setMakeCookie(response, request);
				
			}else{
			//이전 쿠키가 있다면 쿠키 시간을 더 연장시킨다.
				CookieUtil.setCookie(response, com+"-"+"id", cookie_id);
				req.put("cookie_id",cookie_id);
			}
			
			before_url		=	CookieUtil.getCookie(request, com+"-"+"beforeURL");
			if(before_url != null){
				req.put("before_url",before_url);
			}
			
			//2. 클릭정보를 담을 쿠키를 만든다.
				setHotCookie(response, request);
			
			
			//3. 이전 클릭 컨턴트가 존재한다면 그 정보를 쿠키에서 꺼내온다.
				before_log_time	=	CookieUtil.getCookie(request, com+"-"+"beforeURL_click_time");

				if(before_log_time != null){
					before_staying_time = (startTime - Long.parseLong(before_log_time))/1000000000;
				}
				
				req.put("before_staying_time", before_staying_time+"");
			//4. 현재 쿠키 정보를 시스템 로그에 넣는다.
				
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	public String destroy(HttpServletResponse response, HttpServletRequest request){
		try {
			endTime	=	System.nanoTime();
			loading_time	=	(endTime - startTime)/1000000;
			req.put("loadingTime",loading_time+"");
			Transaction.start(request);		
			String queryName = "systemLogger.logging";
			String	query 	=	mappingQuery(request, queryName);
			simpleExecuteUpdate(request, query, queryName);
			Transaction.end(request);
			req.clear();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return loading_time +" ms";
	}	
	
	
	public void setMakeCookie(HttpServletResponse response, HttpServletRequest request){
		try {
			cookie_id = UtilMaster.getToday("yyyyMMdd-kk:mm:ss")+"|"+session_id;
			CookieUtil.setCookie(response, com+"-"+"id", cookie_id);
			//System.out.println("새로운 쿠키를 발급했다"+ cookie_id);
			req.put("cookie_id",cookie_id);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	public void setHotCookie(HttpServletResponse response, HttpServletRequest request){
		try {
			CookieUtil.setCookie(response, com+"-"+"beforeURL", contents_url,60*60*24);
			CookieUtil.setCookie(response, com+"-"+"beforeURL_click_time", System.nanoTime()+"");
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	public void setTodayUniqeCookie(HttpServletResponse response, HttpServletRequest request){
		try {
			CookieUtil.setCookie(response, com+"-"+"today", UtilMaster.getToday("yyyyMMdd"), -1);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
    public Row getRequestInfo(HttpServletRequest request){
        Row reqParam = AutoMapper.getRequest(request);
        AutoMapper.setAttribues(request, reqParam);
        request.setAttribute("_request", reqParam);
        return reqParam;
    }
    
    public String getQuery(String index){
        String query = null;
        try
        {
            query = XMLInMemory.get(index);
        }
        catch(XMLQueryException e)
        {
            e.printStackTrace();
        }
        return query;
    }

    public String mappingQuery(HttpServletRequest request, String index){
        String query = null;
        query = VTLTranslator.getDecode(getQuery(index), (HashMap)request.getAttribute("_request"));
        return query;
    }

    public String mappingQuery(HashMap requestMap, String index){
        String query = null;
        query = VTLTranslator.getDecode(getQuery(index), requestMap);
        return query;
    }

    public int simpleExecuteQuery(HttpServletRequest request, String query, String queryName)throws SQLException{
        Statement stmt = null;
        ResultSet rs = null;
        ArrayList LIST = null;
        Row columnIndexRow = new Row();
        boolean rowChecked = true;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        ResultSetMetaData rsmt = rs.getMetaData();
        int columsize = rsmt.getColumnCount();
        Row hm = null;
        LIST = new ArrayList();
        for(; rs.next(); LIST.add(hm))
        {
            hm = new Row();
            for(int i = 1; i < columsize + 1; i++)
            {
                hm.put(rsmt.getColumnName(i), rs.getString(rsmt.getColumnName(i)));
                if(rowChecked)
                    columnIndexRow.put((new StringBuffer(String.valueOf(i))).toString(), rsmt.getColumnName(i));
            }

            rowChecked = false;
        }

        request.setAttribute(queryName, LIST);
        request.setAttribute(queryName + ".COLUMN_LIST", columnIndexRow);
        request.setAttribute(queryName + ".TOTAL", LIST.size()+"");
        return rs.getRow();
    }

    public Row simpleExecuteQueryGetOneRow(HttpServletRequest request, String query, String queryName)throws SQLException{
        Statement stmt = null;
        ResultSet rs = null;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        ResultSetMetaData rsmt = rs.getMetaData();
        int columsize = rsmt.getColumnCount();
        Row row  = new Row();;
        if(rs.next())        {
            row = new Row();
            for(int i = 1; i < columsize + 1; i++)
                row.put(rsmt.getColumnName(i), rs.getString(rsmt.getColumnName(i)));

        }
        request.setAttribute(queryName, row);
        return row;
    }

    public int simpleExecuteUpdate(HttpServletRequest request, String query, String queryName) throws SQLException{
        Statement stmt = null;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        stmt = con.createStatement();
        int result = stmt.executeUpdate(query);
        request.setAttribute(queryName, (new StringBuffer(String.valueOf(result))).toString());
        return result;
    }

    public int preparedExecuteUpdate(HttpServletRequest request, HashMap requestMap, String preparedIndex[], String query) throws SQLException{
        PreparedStatement psmt = null;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        psmt = con.prepareStatement(query);
        try
        {
            UtilMaster.consoleOut("xframe.console.VTL.preparedParameter.show", "preparedParameter {{");
            for(int i = 0; i < preparedIndex.length; i++)
            {
                UtilMaster.consoleOut("xframe.console.VTL.preparedParameter.show", "[" +i+"] : "+preparedIndex[i]+" : "+  requestMap.get(preparedIndex[i]));
                psmt.setObject(i + 1, requestMap.get(preparedIndex[i]));
            }

            UtilMaster.consoleOut("xframe.console.VTL.preparedParameter.show", "}} preparedParameter");
        }catch(XMLQueryException e){
            e.printStackTrace();
        }
        int returnValue = psmt.executeUpdate();
        psmt.close();
        return returnValue;
    }

}
